//
//  CXsearchController.m
//  搜索页面的封装
//
//  Created by 蔡翔 on 16/7/28.
//  Copyright © 2016年 蔡翔. All rights reserved.
//

#import "CXSearchController.h"
#import "CXSearchSectionModel.h"
#import "CXSearchModel.h"
#import "CXSearchCollectionViewCell.h"
#import "SelectCollectionReusableView.h"
#import "SelectCollectionLayout.h"
#import "CXDBHandle.h"
#import "GoodsListViewController.h"
#import "AppTools.h"
#import "SeardhModel.h"
static NSString *const cxSearchCollectionViewCell = @"CXSearchCollectionViewCell";

static NSString *const headerViewIden = @"HeadViewIden";

@interface CXSearchController()<UICollectionViewDataSource,UICollectionViewDelegate,SelectCollectionCellDelegate,UICollectionReusableViewButtonDelegate,UITextFieldDelegate>

/**
 *  存储网络请求的热搜，与本地缓存的历史搜索model数组
 */
@property (nonatomic, strong) NSMutableArray *sectionArray;
/**
 *  存搜索的数组 字典
 */
@property (nonatomic,strong) NSMutableArray *searchArray;

@property (strong, nonatomic)  UICollectionView *cxSearchCollectionView;

@property (strong, nonatomic)  UITextField *cxSearchTextField;

@property (strong, nonatomic) UIView *goodsListView;
@property (nonatomic, strong) NSMutableArray *hosArray;
@property (nonatomic, strong) NSMutableArray *hotArray;
@end

@implementation CXSearchController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    [self prepareData];
    
    [self createNaviBar];
    
    [self createSubviews];
    
    [self addChildViewControllers];
    
    /***  可以做实时搜索*/
//    [self.cxSearchTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
//    self.navigationItem.title = @"添加地址";
    
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_but_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction)];
    backItem.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = backItem;
    [self create];
    
}
-(void)create{
    self.hosArray = [NSMutableArray array];
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=GetSearchJl&userid=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"]] success:^(id result) {
//        NSLog(@"%@",result);
        for (NSMutableDictionary *dic in [result[0] objectForKey:@"date"]) {
            SeardhModel *model = [[SeardhModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.hosArray addObject:model];
            
        }
        [self.cxSearchCollectionView reloadData];

        
    } error:^(NSError *error) {
        
        
    }];
    self.hotArray = [NSMutableArray array];
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=GetHotSearchJl"] success:^(id result) {
        //        NSLog(@"%@",result);
        for (NSMutableDictionary *dic in [result[0] objectForKey:@"date"]) {
            SeardhModel *model = [[SeardhModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.hotArray addObject:model];
            
        }
        [self.cxSearchCollectionView reloadData];
        
        
    } error:^(NSError *error) {
        
        
    }];
}
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addChildViewControllers{
    GoodsListViewController *goodListVC = [[GoodsListViewController alloc] init];
    [self addChildViewController:goodListVC];
    goodListVC.view.frame = CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight - kNavigationBarHeight);
    self.goodsListView = goodListVC.view;
    [self.view addSubview:self.goodsListView];
    self.goodsListView.hidden = YES;
}

- (void)createSubviews{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, kUIScreenWidth , kUIScreenHeight - kNavigationBarHeight)];
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    scrollView.delegate = self;
    self.cxSearchCollectionView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height + 1);
    [scrollView addSubview:self.cxSearchCollectionView];
    scrollView.contentSize = self.cxSearchCollectionView.bounds.size;
}

- (void)createNaviBar{
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [backBtn  setBackgroundImage:[UIImage imageNamed:@"nav_but_back_xq"] forState:(UIControlStateNormal)];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
    backBtn.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn setTitle:@"搜索" forState:(UIControlStateNormal)];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    btn.frame = CGRectMake(0, 0, 50, 25);
    btn.layer.cornerRadius = 5;
    btn.clipsToBounds = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
    searchView.backgroundColor = [UIColor colorWithWhite:0.969 alpha:1.000];
    
    searchView.layer.cornerRadius = 5;
    searchView.clipsToBounds = YES;
    
    UIImageView *searchImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nav_icon_sousuo"]];
    searchImg.frame = CGRectMake(5, 5, 20, 20);
    [searchView addSubview:searchImg];
    
    self.cxSearchTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(searchImg.frame)+5 , 2.5, 180, 25)];
    self.cxSearchTextField.font = [UIFont systemFontOfSize:15];
    self.cxSearchTextField.text = @"麻将机";
    self.cxSearchTextField.delegate = self;
    [searchView addSubview:self.cxSearchTextField];
    self.navigationItem.titleView = searchView;
}

//这个方法是返回 Header的大小 size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(50, 50);
}

- (void)back:(UIBarButtonItem *)bar{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchAction:(UIBarButtonItem *)barItem{
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=InsertSearchJl&values=%@&userid=%@",self.cxSearchTextField.text,[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"]] success:^(id result) {
        NSLog(@"%@",result);
        
    } error:^(NSError *error) {
        
        
    }];
    
    
    if ([[self.cxSearchTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
        [self.cxSearchTextField resignFirstResponder];
    }
    /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
//    if ([self.searchArray containsObject:[NSDictionary dictionaryWithObject:self.cxSearchTextField.text forKey:@"content_name"]]) {
//    }
//    
    [self reloadData:self.cxSearchTextField.text];
    
    self.goodsListView.hidden = NO;
}

- (void)prepareData
{
    /**
     *  测试数据 ，字段暂时 只用一个 titleString，后续可以根据需求 相应加入新的字段
     */
    
    /***  去数据查看 是否有数据*/
    NSMutableArray *testArray = [@[] mutableCopy];
    
    NSDictionary *parmDict  = @{@"category":@"1"};
    NSDictionary *dbDictionary =  [CXDBHandle statusesWithParams:parmDict];
    
    if (dbDictionary.count) {
        [testArray addObject:dbDictionary];
        [self.searchArray addObjectsFromArray:dbDictionary[@"section_content"]];
    }
    
//    NSArray *array =@[
//  @{@"content_name":@"化妆棉"},
//  @{@"content_name":@"面膜"},
//  @{@"content_name":@"口红"},
//  @{@"content_name":@"眼霜"},
//  @{@"content_name":@"洗面奶"},
//  @{@"content_name":@"防晒霜"},
//  @{@"content_name":@"补水"},
//  @{@"content_name":@"香水"},
//  @{@"content_name":@"眉笔"}
//  ];
    self.hosArray = [NSMutableArray array];
    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=GetSearchJl&userid=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"]] success:^(id result) {
        NSLog(@"%@",result);
        for (NSMutableDictionary *dic in [result[0] objectForKey:@"date"]) {
//            NSDictionary *d = @{@"content_name":[dic objectForKey:@"values"]};
            SeardhModel *model = [[SeardhModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
//            CXSearchSectionModel *model = [[CXSearchSectionModel alloc]init];
//            CXSearchModel *model = [[CXSearchModel alloc] init];
//            model.content_name = [dic objectForKey:@"values"];
            [self.searchArray addObject:model];
//            [self.searchArray addObject:d];
            
        }
        [self.cxSearchCollectionView reloadData];
        
        
    } error:^(NSError *error) {
        
        
    }];

//    NSDictionary *testDict = @{@"section_id":@"1",@"section_title":@"热搜",@"section_content":@[@{@"content_name":@"化妆棉"},@{@"content_name":@"面膜"},@{@"content_name":@"口红"},@{@"content_name":@"眼霜"},@{@"content_name":@"洗面奶"},@{@"content_name":@"防晒霜"},@{@"content_name":@"补水"},@{@"content_name":@"香水"},@{@"content_name":@"眉笔"}]};
    NSDictionary *testDict = @{@"section_id":@"1",@"section_title":@"热搜",@"section_content":self.hosArray};
    NSLog(@"%@",self.hosArray);
    
    [testArray addObject:testDict];
    
    
    for (NSDictionary *sectionDict in testArray) {
        CXSearchSectionModel *model = [[CXSearchSectionModel alloc]initWithDictionary:sectionDict];
        [self.sectionArray addObject:model];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self.cxSearchTextField becomeFirstResponder];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.hosArray.count;
    }
    return self.hotArray.count;
//    CXSearchSectionModel *sectionModel =  self.sectionArray[section];
//    return sectionModel.section_contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CXSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cxSearchCollectionViewCell forIndexPath:indexPath];
//    CXSearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
//    CXSearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
    
    
//    [cell.contentButton setTitle:contentModel.content_name forState:UIControlStateNormal];
    if (indexPath.section == 0) {
        SeardhModel *model = self.hosArray[indexPath.row];
        [cell.contentButton setTitle:model.values forState:UIControlStateNormal];
    }
    if (indexPath.section == 1) {
        SeardhModel *model = self.hotArray[indexPath.row];
        [cell.contentButton setTitle:model.values forState:UIControlStateNormal];
    }
    cell.selectDelegate = self;
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        SelectCollectionReusableView* view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIden forIndexPath:indexPath];
        view.delectDelegate = self;
//        CXSearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
//        [view setText:sectionModel.section_title];
        if (indexPath.section == 0) {
            [view setText:@"历史"];

        }
        if (indexPath.section == 1) {
            [view setText:@"热搜"];
            
        }

        /***  此处完全 也可以自定义自己想要的模型对应放入*/
        if(indexPath.section == 0 && self.sectionArray.count > 1)
        {
            [view setImage:@"cxCool"];
            view.delectButton.hidden = NO;
        }else{
            [view setImage:@"cxSearch"];
            view.delectButton.hidden = YES;
        }
        reusableview = view;
    }
    return reusableview;
}

- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    CXSearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
//    if (sectionModel.section_contentArray.count > 0) {
//        CXSearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
    if (indexPath.section == 0) {
        SeardhModel *model = self.hosArray[indexPath.row];
        return [CXSearchCollectionViewCell getSizeWithText:model.values];

    }
    if (indexPath.section == 1) {
        SeardhModel *model = self.hotArray[indexPath.row];
        return [CXSearchCollectionViewCell getSizeWithText:model.values];
        
    }
//    }
    return CGSizeMake(80, 24);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

#pragma mark - SelectCollectionCellDelegate
- (void)selectButttonClick:(CXSearchCollectionViewCell *)cell;
{
    NSIndexPath* indexPath = [self.cxSearchCollectionView indexPathForCell:cell];
    CXSearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
    CXSearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
    NSLog(@"您选的内容是：%@",contentModel.content_name);
    
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"您该去搜索 %@ 的相关内容了",contentModel.content_name] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了！", nil];
    [al show];
}

#pragma mark - UICollectionReusableViewButtonDelegate
- (void)delectData:(SelectCollectionReusableView *)view;
{
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeObjectAtIndex:0];
        [self.searchArray removeAllObjects];
        [self.cxSearchCollectionView reloadData];
        [CXDBHandle saveStatuses:@{} andParam:@{@"category":@"1"}];
    }
}
#pragma mark - scrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.cxSearchTextField resignFirstResponder];
}
#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
        [textField resignFirstResponder];
        return NO;
    }
    /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
    if ([self.searchArray containsObject:[NSDictionary dictionaryWithObject:textField.text forKey:@"content_name"]]) {
        return YES;
    }
    
    [self reloadData:textField.text];
    
    self.goodsListView.hidden = NO;
    
    return YES;
}
- (void)reloadData:(NSString *)textString
{
    [self.searchArray addObject:[NSDictionary dictionaryWithObject:textString forKey:@"content_name"]];
    
    NSDictionary *searchDict = @{@"section_id":@"2",@"section_title":@"历史记录",@"section_content":self.searchArray};
    
    /***由于数据量并不大 这样每次存入再删除没问题  存数据库*/
    NSDictionary *parmDict  = @{@"category":@"1"};
    [CXDBHandle saveStatuses:searchDict andParam:parmDict];
    
    CXSearchSectionModel *model = [[CXSearchSectionModel alloc]initWithDictionary:searchDict];
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeObjectAtIndex:0];
    }
    [self.sectionArray insertObject:model atIndex:0];
    [self.cxSearchCollectionView reloadData];
//    self.cxSearchTextField.text = @"";
}

#pragma mark - LazyLoad
- (UICollectionView *)cxSearchCollectionView{
    if (!_cxSearchCollectionView) {
        
        self.cxSearchCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[SelectCollectionLayout alloc] init]];
        _cxSearchCollectionView.backgroundColor = [UIColor whiteColor];
        [_cxSearchCollectionView registerClass:[SelectCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIden];
        [_cxSearchCollectionView registerNib:[UINib nibWithNibName:@"CXSearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cxSearchCollectionViewCell];
        _cxSearchCollectionView.delegate = self;
        _cxSearchCollectionView.dataSource = self;
    }
    return _cxSearchCollectionView;
}

-(NSMutableArray *)sectionArray
{
    if (_sectionArray == nil) {
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}

-(NSMutableArray *)searchArray
{
    if (_searchArray == nil) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}


@end
